package org.zhou.sa_tokent.Interceptor;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
//import com.yunyu.back_common.entity.ServerResponse;
//import com.yunyu.back_common.state.StateCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.function.ServerResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 */
@ControllerAdvice // 可指定包前缀，比如：(basePackages = "com.pj.admin")
public class GlobalException {

    // 在当前类每个方法进入之前触发的操作
    @ModelAttribute
    public void get(HttpServletRequest request) throws IOException {

    }

    @ResponseBody
    @ExceptionHandler
    public ServerResponse handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 不同异常返回不同状态码
        ServerResponse serverResponse = new ServerResponse();
        if (e instanceof NotLoginException) {
            // 如果是未登录异常
            NotLoginException ee = (NotLoginException) e;
            serverResponse.setMessage("用户未登录!");
            serverResponse.setCode(StateCode.NOT_LOGIN);
        } else if(e instanceof NotRoleException) {
            // 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            serverResponse.setCode(StateCode.NOT_JUR);
            serverResponse.setMessage("角色异常!");
        } else if(e instanceof NotPermissionException) {
            // 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            serverResponse.setMessage("权限异常!");
            serverResponse.setCode(StateCode.NOT_JUR);
        } else if(e instanceof DisableLoginException) {
            // 如果是被封禁异常
            DisableLoginException ee = (DisableLoginException) e;
            serverResponse.setMessage("封禁异常!");
        } else {
            // 普通异常, 输出：500 + 异常信息
            serverResponse.setMessage("服务器内部错误!");
            serverResponse.setData(e);
            serverResponse.setCode(StateCode.ERROR);
            System.out.println(e);
        }
        return serverResponse;
    }
}
